#include "Cond.hpp"

#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <unistd.h>

pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;   // 条件变量

int num = 1;

void *ThreadFunc(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&g_lock);         // 加锁
        pthread_cond_wait(&g_cond, &g_lock); // 等待
        std::cout << name << " 修改num:" << num << std::endl;
        num++;
        pthread_mutex_unlock(&g_lock); // 解锁
    }
    return nullptr;
}

int main()
{
    std::vector<pthread_t> threads;
    for (int i = 0; i < 5; i++)
    {
        pthread_t tid;
        char *name = new char[64];
        snprintf(name, 64, "thread - %d", i);
        int n = pthread_create(&tid, nullptr, ThreadFunc, name);
        if (n != 0)
            std::cerr << "pthread_create error" << std::endl;
        threads.push_back(tid);
    }

    sleep(2);
    while (true)
    {
        // std::cout << "唤醒一个线程" << std::endl;
        // pthread_cond_signal(&g_cond);
        std::cout << "唤醒所有线程" << std::endl;
        pthread_cond_broadcast(&g_cond);
        sleep(1);
    }

    for (auto &id : threads)
    {
        pthread_join(id, nullptr);
    }

    return 0;
}